package com.wwx.demo.servlet;

import com.alibaba.fastjson.JSON;
import com.wwx.demo.entity.Result;
import com.wwx.demo.entity.Tiger;
import com.wwx.demo.service.api.TigerService;
import com.wwx.demo.service.impl.TigerServiceImpl;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;

@WebServlet(name = "TigerServletUpdate", value = "/TigerServletUpdate")
public class TigerServletUpdate extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        TigerService tigerService = new TigerServiceImpl();

        // 1、从请求体读取 JSON 数据
        // [1]通过 request 对象获取读取请求体的输入流
        BufferedReader reader = request.getReader();

        // [2]创建 StringBuilder 对象存放循环读取请求体时的每一部分数据
        StringBuilder stringBuilder = new StringBuilder("");

        // [3]声明变量，存储读取到的每一行
        String line = null;

        // [4]循环读取请求体
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }

        // [5]把 StringBuilder 转换为字符串
        String jsonString = stringBuilder.toString();

        // 2、把 JSON 数据从字符串转换为 Java 实体类类型，得到 Tiger 对象
        Tiger tiger = JSON.parseObject(jsonString, Tiger.class);

        // 3、调用 Service 方法执行更新
        tigerService.updateTiger(tiger);

        // 4、返回响应
        response.getWriter().write(JSON.toJSONString(Result.ok()));
    }
}
